<?php

namespace App\V3\V3_2_6\Controllers;

use App\V3\V3_2_6\Services\SmsService;
use App\Http\Controllers\Controller;
use App\V3\V3_2_6\Services\LoginService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use App\Api\Models\OperationLogModel;

class LoginController extends Controller
{
    //发送验证码
    public function sendCode(Request $request)
    {
        $result = self::checkMobile($request->all());//校验手机号

        if(!in_array($request->code_type, [0,1])) {
            return ['code' => 1, 'msg' => '验证码类型错误', 'data' => ''];
        }

        if($result == '') {
            if($request->code_type) {
                if(Redis::exists($request->mobile.'_mobile_login')) {
                    return ['code' => 1, 'msg' => '验证码已发送，请勿重新点击', 'data' => ''];
                }
            }
            else {
                if(Redis::exists($request->mobile.'_change_pwd')) {
                    return ['code' => 1, 'msg' => '验证码已发送，请勿重新点击', 'data' => ''];
                }
            }

            return response()->json(SmsService::sendCode($request->mobile, $request->code_type));
        }
        else {
            return response()->json([
                'code' => 1,
                'msg' => $result,
                'data' => ''
            ]);
        }
    }

    //校验手机号
    private function checkMobile($data) {
        $messages = [
            'mobile.required' => '手机号不能为空，请输入手机号',
            'mobile.regex' => '手机号格式错误，请重试',
        ];

        $validator = Validator::make($data, [
            'mobile' => 'required|regex:/^1[3456789][0-9]{9}$/',
        ], $messages);

        return $validator->errors()->first();
    }

    public function login(Request $request)
    {
        $validator = Validator::make($data = $request->all(), [
            'device' => [
                'required',
                'integer',
                Rule::In([1,2,3,4,5]),
            ],//物料类型所属二级分类id
        ],
            [
                'device.required' => '参数`device`缺失',
                'device.integer' => '参数`device`只能为数字',
                'device.in' => '参数`device`不合法',
            ]
        );

        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }

        $minicode = empty($request->mini_code)?'':$request->mini_code;

        if(in_array($request->type, [0, 1, 2])) {
            //type:0->验证码登录(主账号);1->密码登录(子账号);2->主账号密码登录
            switch($request->type) {
                case 0:
                    $remark="主账号验证码登录";
                    //默认验证码登录
                    if($request->code == 666666) {
                        $result = LoginService::defaultCodeLog(
                            $data,
                            empty($request->device_id)?0:$request->device_id,
                            $minicode
                            );
                        $res = OperationLogModel::insert([
                            'main_id'=>!empty($result['data']['parent_id'])?$result['data']['parent_id']:0,
                            'user_id'=>!empty($result['data']['user_id'])?$result['data']['user_id']:0,
                            'remark'=>$remark,
                            'data'=>json_encode($data,JSON_UNESCAPED_UNICODE),
                            'ip'=>$_SERVER["REMOTE_ADDR"],
                            'created_at'=>time(),
                        ]);

                        if(!$res){
                            return response()->json(['code' => 1,'msg' => '操作日志插入失败','data' => '']);
                        }
                        return response()->json($result);
                    }

                    $result = self::checkMobile($request->all());//校验手机号

                    if(!$result == '') {
                        return response()->json([
                            'code' => 1,
                            'msg' => $result,
                            'data' => ''
                        ]);
                    }

                    $result = LoginService::mainLogin(
                        $request->mobile,
                        $request->code,
                        $request->device,
                        $minicode,
                        empty($request->bind_id)?0:$request->bind_id,
                        empty($request->device_id)?0:$request->device_id
                    );
                    break;
                case 1:
                    $remark="子账号（员工）登录";
                    if(empty($request->username)) {
                        return response()->json([
                            'code' => 1,
                            'msg' => '请输入用户名',
                            'data' => ''
                        ]);
                    }

                    if(empty($request->password)) {
                        return response()->json([
                            'code' => 1,
                            'msg' => '请输入密码',
                            'data' => ''
                        ]);
                    }

                    if(empty($request->user_id)) {
                        return response()->json([
                            'code' => 1,
                            'msg' => '请输入用户ID',
                            'data' => ''
                        ]);
                    }

                    $result = LoginService::userLogin(
                        $request->username,
                        $request->password,
                        $request->user_id,
                        $request->device,
                        empty($request->device_id)?0:$request->device_id,
                        $minicode
                    );


//                    $result = LoginService::userLogin1(
//                        $request->username,
//                        $request->password,
//                        $request->device,
//                        empty($request->device_id)?0:$request->device_id,
//                        $minicode
//                    );
                    break;
                case 2:
                    $remark="主账号密码登录";
                    if(!empty($data['username'])) $data['mobile'] = $data['username'];
                    $checkMobile = self::checkMobile($data);

                    if($checkMobile != '') {
                        return response()->json([
                            'code' => 1,
                            'msg' => $checkMobile,
                            'data' => ''
                        ]);
                    }

                    if(empty($data['pwd'])) {
                        return response()->json([
                            'code' => 1,
                            'msg' => '请输入密码',
                            'data' => ''
                        ]);
                    }

                    $result = LoginService::pwdLogin(
                        $data['mobile'],
                        $request->pwd,
                        $request->device,
                        $minicode,
                        empty($request->bind_id)?0:$request->bind_id,
                        empty($request->device_id)?0:$request->device_id
                    );
                    break;
            }
            $res = OperationLogModel::insert([
                'main_id'=>!empty($result['data']['parent_id'])?$result['data']['parent_id']:0,
                'user_id'=>!empty($result['data']['user_id'])?$result['data']['user_id']:0,
                'remark'=>$remark,
                'data'=>json_encode($data,JSON_UNESCAPED_UNICODE),
                'ip'=>$_SERVER["REMOTE_ADDR"],
                'created_at'=>time(),
            ]);

            if(!$res){
                return response()->json(['code' => 1,'msg' => '操作日志插入失败','data' => '']);
            }
            return $result;
        }
        else {
            return response()->json([
                'code' => 1,
                'msg' => '参数`type`不合法',
                'data' => ''
            ]);
        }
    }
}
